# -*- coding: utf-8 -*-
import sys
import os
import pandas as pd
import shutil
from PyQt6.QtWidgets import (QApplication, QMainWindow, QPushButton, QFileDialog,
                           QVBoxLayout, QHBoxLayout, QWidget, QLabel, QSpinBox,
                           QTableWidget, QTableWidgetItem, QMessageBox, QGroupBox,
                           QListWidget, QListWidgetItem, QFrame, QSplitter, QHeaderView)
from PyQt6.QtCore import Qt, QMimeData, QPoint
from PyQt6.QtGui import QDrag, QColor, QFont
import random
from src.ui.main_window import PhysicalEducationScheduler

class DraggableListWidget(QListWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setDragEnabled(True)
        self.setAcceptDrops(True)
        self.setDropIndicatorShown(True)
        self.setDefaultDropAction(Qt.DropAction.MoveAction)
    
    def startDrag(self, actions):
        item = self.currentItem()
        if item:
            mime_data = QMimeData()
            class_info = item.data(Qt.ItemDataRole.UserRole)
            # 将文本和二进制数据都设置到MIME数据中
            mime_data.setText(str(class_info))
            # 确保数据是bytes类型
            mime_data.setData("application/x-class-info", str(class_info).encode('utf-8'))
            
            drag = QDrag(self)
            drag.setMimeData(mime_data)
            drag.exec(Qt.DropAction.MoveAction)
    
    def dragEnterEvent(self, event):
        if event.mimeData().hasText():
            event.accept()
        else:
            event.ignore()
    
    def dropEvent(self, event):
        if event.mimeData().hasText():
            event.accept()
            class_info = event.mimeData().text()
            # 添加到未安排列表
            self.addItem(class_info)
            # 通知父窗口更新课表
            self.parent().parent().handle_class_return(class_info)

class ClassCell(QFrame):
    def __init__(self, class_info, parent=None):
        super().__init__(parent)
        self.class_info = class_info
        self.init_ui()
    
    def init_ui(self):
        layout = QVBoxLayout(self)
        layout.setContentsMargins(2, 2, 2, 2)  # 减小边距
        layout.setSpacing(0)  # 减小间距
        
        text = "%s-%s-%s年级\n(男:%d 女:%d)" % (
            self.class_info['college'],
            self.class_info['major'],
            self.class_info['grade'],
            self.class_info['male'],
            self.class_info['female']
        )
        label = QLabel(text)
        label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        
        # 设置更小的字体
        font = QFont()
        font.setPointSize(9)  # 减小字体大小
        font.setBold(True)    # 保持粗体
        label.setFont(font)
        
        # 设置文字颜色和样式
        label.setStyleSheet("""
            color: black;
            padding: 2px;
        """)
        
        layout.addWidget(label)
        
        # 设置背景色为浅灰色，并添加边框
        self.setStyleSheet("""
            QFrame {
                background-color: #f0f0f0;
                border: 1px solid #999999;
                border-radius: 4px;
                margin: 1px;
            }
        """)
        
        # 设置更小的最小尺寸
        self.setMinimumHeight(50)  # 减小高度
        self.setMaximumHeight(60)  # 设置最大高度
        
        # 启用鼠标追踪
        self.setMouseTracking(True)
    
    def mousePressEvent(self, event):
        if event.button() == Qt.MouseButton.LeftButton:
            # 创建拖动对象
            drag = QDrag(self)
            mime_data = QMimeData()
            
            # 获取源位置信息
            container = self.parent()
            if container:
                table_widget = container.parent()
                if isinstance(table_widget, QTableWidget):
                    row = table_widget.indexAt(container.pos()).row()
                    col = table_widget.indexAt(container.pos()).column()
                    source_pos = {'row': row, 'col': col}
                    
                    # 设置拖动数据
                    mime_data.setText(self.format_class_info())
                    mime_data.setData("application/x-class-info", 
                                    str((self.class_info, source_pos)).encode())
                    drag.setMimeData(mime_data)
                    
                    # 开始拖动
                    drag.exec(Qt.DropAction.MoveAction)
    
    def format_class_info(self):
        return "%s-%s-%s年级(男:%d 女:%d)" % (
            self.class_info['college'],
            self.class_info['major'],
            self.class_info['grade'],
            self.class_info['male'],
            self.class_info['female']
        )

class ScheduleCell(QTableWidgetItem):
    def __init__(self, text=""):
        super().__init__(text)
        self.setFlags(self.flags() | Qt.ItemFlag.ItemIsDropEnabled)
        self.classes = []  # 存储该时间段安排的班级信息
        self.widgets = []  # 存储显示的ClassCell部件

class ScheduleTable(QTableWidget):
    def __init__(self, parent=None):
        super().__init__(3, 5, parent)
        self.setAcceptDrops(True)
        self.verticalHeader().setDefaultSectionSize(120)   # 减小行高
        self.horizontalHeader().setDefaultSectionSize(200) # 减小列宽
        
        # 设置表头字体
        header_font = QFont()
        header_font.setPointSize(10)  # 减小表头字体
        header_font.setBold(True)
        self.horizontalHeader().setFont(header_font)
        self.verticalHeader().setFont(header_font)
        
        # 设置表格样式
        self.setStyleSheet("""
            QTableWidget {
                gridline-color: #cccccc;
                background-color: white;
            }
            QTableWidget::item {
                padding: 2px;
            }
            QHeaderView::section {
                background-color: #f0f0f0;
                padding: 4px;
                border: 1px solid #cccccc;
            }
        """)
        
        # 设置表格自动调整大小
        self.horizontalHeader().setStretchLastSection(True)
        self.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeMode.Stretch)
        self.verticalHeader().setSectionResizeMode(QHeaderView.ResizeMode.ResizeToContents)
    
    def dragEnterEvent(self, event):
        if event.mimeData().hasText():
            event.acceptProposedAction()
        else:
            event.ignore()
    
    def dragMoveEvent(self, event):
        if event.mimeData().hasText():
            event.acceptProposedAction()
        else:
            event.ignore()
    
    def dropEvent(self, event):
        if event.mimeData().hasText():
            event.acceptProposedAction()
            pos = event.position().toPoint()
            item = self.itemAt(pos)
            if item:
                row = self.row(item)
                col = self.column(item)
                # 获取主窗口实例
                main_window = self.window()
                if isinstance(main_window, PhysicalEducationScheduler):
                    # 获取源位置信息（如果是从课表中拖动的）
                    source_data = event.mimeData().data("application/x-class-info").data()
                    if source_data:
                        try:
                            class_info, source_pos = eval(source_data.decode())
                            main_window.handle_class_move(class_info, source_pos, row, col)
                        except:
                            # 如果解析失败，说明是从未安排列表拖动的
                            main_window.handle_class_drop(event.mimeData().text(), row, col)
                    else:
                        main_window.handle_class_drop(event.mimeData().text(), row, col)

class PhysicalEducationScheduler(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("体育课程安排系统")
        self.setGeometry(100, 100, 1400, 800)
        
        # 数据存储
        self.student_data = None
        self.max_students_per_day = 8000
        self.schedule_table = None
        self.daily_stats = {}
        self.all_classes = []
        self.unscheduled_classes = []
        self.time_slots = ['第一节', '第二节', '第三节']
        self.days = ['周一', '周二', '周三', '周四', '周五']
        
        self.init_ui()
    
    def init_ui(self):
        # 创建中央部件
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        
        # 创建主布局
        main_layout = QHBoxLayout(central_widget)
        
        # 创建分割器
        splitter = QSplitter(Qt.Orientation.Horizontal)
        splitter.setHandleWidth(5)  # 设置分割条宽度
        splitter.setStyleSheet("""
            QSplitter::handle {
                background-color: #cccccc;
                border: 1px solid #999999;
            }
            QSplitter::handle:hover {
                background-color: #bbbbbb;
            }
        """)
        
        # 左侧面板
        left_widget = QWidget()
        left_layout = QVBoxLayout(left_widget)
        
        # 控制区域
        control_group = QGroupBox("控制面板")
        control_layout = QVBoxLayout()
        
        # 导入按钮
        import_btn = QPushButton("导入Excel数据", self)
        import_btn.clicked.connect(self.import_excel)
        control_layout.addWidget(import_btn)
        
        # 添加模板下载按钮
        template_btn = QPushButton("下载Excel模板", self)
        template_btn.clicked.connect(self.download_template)
        control_layout.addWidget(template_btn)
        
        # 添加自动排课按钮
        auto_schedule_btn = QPushButton("自动排课", self)
        auto_schedule_btn.clicked.connect(self.auto_schedule)
        control_layout.addWidget(auto_schedule_btn)
        
        # 添加清空课表按钮
        clear_btn = QPushButton("清空课表", self)
        clear_btn.clicked.connect(self.clear_schedule_with_confirm)
        control_layout.addWidget(clear_btn)
        
        # 每日学生上限设置
        limit_layout = QHBoxLayout()
        limit_label = QLabel("每日学生上限:", self)
        limit_layout.addWidget(limit_label)
        
        self.limit_spinbox = QSpinBox(self)
        self.limit_spinbox.setRange(1, 10000)
        self.limit_spinbox.setValue(self.max_students_per_day)
        self.limit_spinbox.valueChanged.connect(self.update_max_students)
        limit_layout.addWidget(self.limit_spinbox)
        control_layout.addLayout(limit_layout)
        
        control_group.setLayout(control_layout)
        left_layout.addWidget(control_group)
        
        # 未安排课程列表
        unscheduled_group = QGroupBox("未安排课程")
        unscheduled_layout = QVBoxLayout()
        self.unscheduled_list = DraggableListWidget()
        unscheduled_layout.addWidget(self.unscheduled_list)
        unscheduled_group.setLayout(unscheduled_layout)
        left_layout.addWidget(unscheduled_group)
        
        # 右侧面板
        right_widget = QWidget()
        right_layout = QVBoxLayout(right_widget)
        
        # 数据统计
        stats_group = QGroupBox("数据统计")
        stats_layout = QVBoxLayout()
        
        # 总体统计
        total_stats_layout = QHBoxLayout()
        self.college_count_label = QLabel("学院数量: 0")
        self.major_count_label = QLabel("专业数量: 0")
        self.total_students_label = QLabel("学生总数: 0")
        self.male_students_label = QLabel("男生总数: 0")
        self.female_students_label = QLabel("女生总数: 0")
        
        total_stats_layout.addWidget(self.college_count_label)
        total_stats_layout.addWidget(self.major_count_label)
        total_stats_layout.addWidget(self.total_students_label)
        total_stats_layout.addWidget(self.male_students_label)
        total_stats_layout.addWidget(self.female_students_label)
        
        stats_layout.addLayout(total_stats_layout)
        
        # 每日统计
        self.daily_stats_labels = {}
        for day in self.days:
            day_label = QLabel(f"{day}安排学生数: 0")
            self.daily_stats_labels[day] = day_label
            stats_layout.addWidget(day_label)
        
        stats_group.setLayout(stats_layout)
        right_layout.addWidget(stats_group)
        
        # 课表
        schedule_group = QGroupBox("课程安排")
        schedule_layout = QVBoxLayout()
        self.schedule_table = ScheduleTable(self)
        self.schedule_table.setHorizontalHeaderLabels(self.days)
        self.schedule_table.setVerticalHeaderLabels(self.time_slots)
        
        # 设置表头样式
        self.schedule_table.horizontalHeader().setStyleSheet("""
            QHeaderView::section {
                background-color: #4a4a4a;
                color: white;
                padding: 5px;
                border: 1px solid #666666;
                font-weight: bold;
            }
        """)
        self.schedule_table.verticalHeader().setStyleSheet("""
            QHeaderView::section {
                background-color: #4a4a4a;
                color: white;
                padding: 5px;
                border: 1px solid #666666;
                font-weight: bold;
            }
        """)
        
        # 设置表格自动调整大小
        self.schedule_table.horizontalHeader().setStretchLastSection(True)
        self.schedule_table.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeMode.Stretch)
        self.schedule_table.verticalHeader().setSectionResizeMode(QHeaderView.ResizeMode.ResizeToContents)
        
        # 初始化课表单元格
        for row in range(3):
            for col in range(5):
                cell = ScheduleCell()
                cell.setTextAlignment(Qt.AlignmentFlag.AlignCenter)
                self.schedule_table.setItem(row, col, cell)
        
        schedule_layout.addWidget(self.schedule_table)
        schedule_group.setLayout(schedule_layout)
        right_layout.addWidget(schedule_group)
        
        # 添加左右面板到分割器
        splitter.addWidget(left_widget)
        splitter.addWidget(right_widget)
        
        # 设置初始分割比例（左:右 = 1:2）
        splitter.setSizes([400, 800])
        
        # 将分割器添加到主布局
        main_layout.addWidget(splitter)
    
    def handle_class_move(self, class_info, source_pos, target_row, target_col):
        """处理课表内的班级移动"""
        if source_pos['row'] == target_row and source_pos['col'] == target_col:
            return  # 如果是同一个位置，不做处理
        
        day = self.days[target_col]
        
        # 检查目标时间段是否可以安排该班级
        # 注意：需要先从源位置移除才能正确计算目标日期的学生数
        source_cell = self.schedule_table.item(source_pos['row'], source_pos['col'])
        if source_cell and source_cell.classes:
            # 从源位置移除班级
            for i, cls in enumerate(source_cell.classes):
                if self.format_class_info(cls) == self.format_class_info(class_info):
                    source_cell.classes.pop(i)
                    self.update_cell_display(source_cell)
                    break
        
        # 检查是否可以安排到目标位置
        if self.can_schedule_class(class_info, day):
            # 更新目标位置
            target_cell = self.schedule_table.item(target_row, target_col)
            if not target_cell.classes:
                target_cell.classes = []
            target_cell.classes.append(class_info)
            self.update_cell_display(target_cell)
        else:
            # 如果不能安排到目标位置，将班级添加回源位置
            source_cell.classes.append(class_info)
            self.update_cell_display(source_cell)
            QMessageBox.warning(self, "警告", "该时间段学生数量超过限制")
        
        # 更新统计信息
        self.update_daily_stats()

    def handle_class_return(self, class_info_text):
        """处理班级被拖回未安排列表"""
        # 在所有时间槽中查找并移除该班级
        for row in range(3):
            for col in range(5):
                cell = self.schedule_table.item(row, col)
                if cell and cell.classes:
                    for class_info in cell.classes[:]:
                        if self.format_class_info(class_info) == class_info_text:
                            cell.classes.remove(class_info)
                            self.update_cell_display(cell)
                            # 将班级添加回未安排列表
                            if class_info not in self.unscheduled_classes:
                                self.unscheduled_classes.append(class_info)
                            break
        
        # 更新未安排列表显示
        self.update_unscheduled_list()
        # 更新统计信息
        self.update_daily_stats()

    def update_cell_display(self, cell):
        """更新单元格显示"""
        # 清除现有的部件
        for widget in cell.widgets:
            self.schedule_table.removeCellWidget(
                self.schedule_table.row(cell),
                self.schedule_table.column(cell)
            )
        cell.widgets.clear()
        
        if cell.classes:
            # 创建容器部件
            container = QWidget()
            layout = QVBoxLayout(container)
            layout.setSpacing(1)  # 减小间距
            layout.setContentsMargins(1, 1, 1, 1)  # 减小边距
            
            # 为每个班级创建可拖动的部件
            for class_info in cell.classes:
                class_widget = ClassCell(class_info)
                layout.addWidget(class_widget)
            
            # 设置单元格的部件
            self.schedule_table.setCellWidget(
                self.schedule_table.row(cell),
                self.schedule_table.column(cell),
                container
            )
            cell.widgets.append(container)
            
            # 调整行高以适应内容
            self.schedule_table.resizeRowToContents(self.schedule_table.row(cell))
        else:
            self.schedule_table.removeCellWidget(
                self.schedule_table.row(cell),
                self.schedule_table.column(cell)
            )

    def update_unscheduled_list(self):
        """更新未安排课程列表"""
        self.unscheduled_list.clear()
        # 按学院、专业、年级排序
        sorted_classes = sorted(self.unscheduled_classes, 
                              key=lambda x: (x['college'], x['major'], x['grade']))
        for class_info in sorted_classes:
            item = QListWidgetItem(self.format_class_info(class_info))
            # 存储完整的班级信息
            item.setData(Qt.ItemDataRole.UserRole, str(class_info))
            self.unscheduled_list.addItem(item)

    def process_imported_data(self):
        """处理导入的数据"""
        if self.student_data is None:
            return
        
        # 清空现有数据
        self.unscheduled_list.clear()
        self.clear_schedule()
        self.all_classes = []
        self.unscheduled_classes = []
        
        # 处理数据
        for _, row in self.student_data.iterrows():
            class_info = {
                'college': row['学院'],
                'major': row['专业'],
                'grade': row['年级'],
                'male': row['男生人数'],
                'female': row['女生人数']
            }
            self.all_classes.append(class_info)
            self.unscheduled_classes.append(class_info)
        
        # 更新未安排列表
        self.update_unscheduled_list()
        
        # 更新统计信息
        self.update_statistics()
    
    def clear_schedule(self):
        for row in range(3):
            for col in range(5):
                cell = self.schedule_table.item(row, col)
                cell.classes = []
                cell.setText("")
    
    def update_statistics(self):
        if self.student_data is not None:
            # 计算统计数据
            college_count = len(self.student_data['学院'].unique())
            major_count = len(self.student_data[['学院', '专业']].drop_duplicates())
            total_male = self.student_data['男生人数'].sum()
            total_female = self.student_data['女生人数'].sum()
            total_students = total_male + total_female
            
            # 更新显示
            self.college_count_label.setText("学院数量: %d" % college_count)
            self.major_count_label.setText("专业数量: %d" % major_count)
            self.total_students_label.setText("学生总数: %d" % total_students)
            self.male_students_label.setText("男生总数: %d" % total_male)
            self.female_students_label.setText("女生总数: %d" % total_female)
    
    def update_max_students(self, value):
        self.max_students_per_day = value
    
    def download_template(self):
        """下载Excel模板文件"""
        # 创建示例数据
        data = {
            '学院': ['示例学院1', '示例学院2'],
            '专业': ['示例专业1', '示例专业2'],
            '年级': [1, 2],
            '男生人数': [30, 25],
            '女生人数': [20, 25]
        }
        
        # 创建DataFrame
        df = pd.DataFrame(data)
        
        # 让用户选择保存位置
        file_name, _ = QFileDialog.getSaveFileName(
            self,
            "保存Excel模板",
            "体育课程安排模板.xlsx",
            "Excel Files (*.xlsx)"
        )
        
        if file_name:
            try:
                # 保存Excel文件
                df.to_excel(file_name, index=False)
                QMessageBox.information(self, "成功", "模板文件已保存")
            except Exception as e:
                QMessageBox.critical(self, "错误", "保存模板文件时出错：%s" % str(e))

    def auto_schedule(self):
        """自动排课功能"""
        if not self.unscheduled_classes:
            QMessageBox.warning(self, "警告", "没有需要安排的班级")
            return
        
        # 创建时间槽列表
        time_slots = []
        for day in self.days:
            for slot in self.time_slots:
                time_slots.append((day, slot))
        
        # 获取每个时间槽当前的学生数
        slot_students = {}
        for day, slot in time_slots:
            col = self.days.index(day)
            row = self.time_slots.index(slot)
            cell = self.schedule_table.item(row, col)
            total = sum(c['male'] + c['female'] for c in cell.classes) if cell.classes else 0
            slot_students[(day, slot)] = total
        
        # 对未安排的班级按人数从大到小排序
        self.unscheduled_classes.sort(key=lambda x: x['male'] + x['female'], reverse=True)
        
        # 尝试为每个未安排的班级找到最佳时间槽
        scheduled_classes = []
        for class_info in self.unscheduled_classes[:]:
            class_size = class_info['male'] + class_info['female']
            
            # 找出可用的时间槽（不超过每日上限）
            available_slots = []
            for day, slot in time_slots:
                # 计算当天的总学生数
                daily_total = sum(
                    slot_students.get((day, time_slot), 0)
                    for time_slot in self.time_slots
                )
                
                if daily_total + class_size <= self.max_students_per_day:
                    current_slot_students = slot_students.get((day, slot), 0)
                    available_slots.append(((day, slot), current_slot_students))
            
            if not available_slots:
                continue
            
            # 按当前学生数从少到多排序时间槽
            available_slots.sort(key=lambda x: x[1])
            
            # 选择学生数最少的时间槽
            best_slot = available_slots[0][0]
            day, slot = best_slot
            
            # 更新时间槽的学生数
            slot_students[best_slot] = slot_students.get(best_slot, 0) + class_size
            
            # 更新课表
            col = self.days.index(day)
            row = self.time_slots.index(slot)
            cell = self.schedule_table.item(row, col)
            cell.classes.append(class_info)
            self.update_cell_display(cell)
            
            # 从未安排列表中移除
            scheduled_classes.append(class_info)
            self.remove_from_unscheduled(self.format_class_info(class_info))
        
        # 更新统计信息
        self.update_daily_stats()
        
        # 显示结果信息
        if scheduled_classes:
            QMessageBox.information(self, "成功", 
                                  "成功安排了%d个班级的课程" % len(scheduled_classes))
        else:
            QMessageBox.warning(self, "警告", 
                              "无法安排任何班级，请检查每日学生上限是否合理")

    def get_daily_student_count(self, day):
        """获取指定日期的学生总数"""
        total = 0
        col = self.days.index(day)
        for row in range(len(self.time_slots)):
            cell = self.schedule_table.item(row, col)
            if cell and cell.classes:
                total += sum(c['male'] + c['female'] for c in cell.classes)
        return total

    def remove_from_unscheduled(self, class_info):
        items = self.unscheduled_list.findItems(class_info, Qt.MatchFlag.MatchExactly)
        if items:
            self.unscheduled_list.takeItem(self.unscheduled_list.row(items[0]))

    def update_daily_stats(self):
        days = ['周一', '周二', '周三', '周四', '周五']
        for day in days:
            total_male = 0
            total_female = 0
            for cell in self.get_day_cells(day):
                if cell and cell.classes:
                    for class_info in cell.classes:
                        total_male += class_info['male']
                        total_female += class_info['female']
            total = total_male + total_female
            self.daily_stats_labels[day].setText(
                "%s安排学生数: %d (男:%d 女:%d)" % (day, total, total_male, total_female)
            )

    def import_excel(self):
        file_name, _ = QFileDialog.getOpenFileName(
            self,
            "选择Excel文件",
            "",
            "Excel Files (*.xlsx *.xls)"
        )
        
        if file_name:
            try:
                self.student_data = pd.read_excel(file_name)
                self.process_imported_data()
            except Exception as e:
                QMessageBox.critical(self, "错误", "导入Excel文件时出错：%s" % str(e))

    def format_class_info(self, class_data):
        return "%s-%s-%s年级(男:%d 女:%d)" % (
            class_data['college'],
            class_data['major'],
            class_data['grade'],
            class_data['male'],
            class_data['female']
        )

    def can_schedule_class(self, class_data, day):
        current_total = sum(
            sum(c['male'] + c['female'] for c in cell.classes)
            for cell in self.get_day_cells(day)
        )
        return current_total + class_data['male'] + class_data['female'] <= self.max_students_per_day

    def get_day_cells(self, day):
        days = ['周一', '周二', '周三', '周四', '周五']
        col = days.index(day)
        return [self.schedule_table.item(row, col) for row in range(3)]

    def clear_schedule_with_confirm(self):
        """清空课表，带确认对话框"""
        reply = QMessageBox.question(
            self,
            "确认清空",
            "确定要清空当前课表吗？所有已安排的课程将返回到未安排列表。",
            QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No,
            QMessageBox.StandardButton.No
        )
        
        if reply == QMessageBox.StandardButton.Yes:
            self.clear_schedule_and_reset()

    def clear_schedule_and_reset(self):
        """清空课表并重置所有相关数据"""
        # 将所有已安排的班级返回到未安排列表
        for row in range(3):
            for col in range(5):
                cell = self.schedule_table.item(row, col)
                if cell and cell.classes:
                    # 将班级添加回未安排列表
                    for class_info in cell.classes:
                        if class_info not in self.unscheduled_classes:
                            self.unscheduled_classes.append(class_info)
                    # 清空单元格
                    cell.classes = []
                    self.update_cell_display(cell)
        
        # 更新未安排列表显示
        self.update_unscheduled_list()
        
        # 更新统计信息
        self.update_daily_stats()
        
        # 显示成功消息
        QMessageBox.information(self, "成功", "课表已清空，所有课程已返回未安排列表")

    def handle_class_drop(self, class_info_text, row, col):
        """处理从未安排列表拖放到课表"""
        day = self.days[col]
        
        # 解析班级信息
        for class_data in self.unscheduled_classes[:]:  # 使用切片创建副本
            if self.format_class_info(class_data) == class_info_text:
                # 检查该时间段是否可以安排该班级
                if self.can_schedule_class(class_data, day):
                    # 更新课表显示
                    cell = self.schedule_table.item(row, col)
                    if not cell.classes:
                        cell.classes = []
                    cell.classes.append(class_data)
                    self.update_cell_display(cell)
                    
                    # 从未安排列表中移除
                    self.unscheduled_classes.remove(class_data)
                    self.update_unscheduled_list()
                    
                    # 更新统计信息
                    self.update_daily_stats()
                else:
                    QMessageBox.warning(self, "警告", "该时间段学生数量超过限制")
                break

def main():
    app = QApplication(sys.argv)
    
    # 设置应用程序样式
    app.setStyle('Fusion')
    
    # 创建并显示主窗口
    window = PhysicalEducationScheduler()
    window.show()
    
    # 运行应用程序
    sys.exit(app.exec())

if __name__ == '__main__':
    main() 